import {
  ActionType,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Col, DatePicker, Divider, Form, Input, InputNumber, message, Popconfirm, Row } from 'antd';
import { useRef, useState } from 'react';
import CreateForm from '@/components/CreateForm';
import services from '@/services/insuredPersonItem';
import React from 'react';

const { queryList, addData, modifyData, deleteData } = services.InsuredPersonItemController

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (id: number | string | null = null, fields: API.InsuredPersonItem, insuredPersonId: any) => {
  const hide = message.loading('正在操作');
  try {
    id ? await modifyData({ id }, { ...fields, insuredPersonId }) : await addData({ ...fields, insuredPersonId });
    hide();
    return true;
  } catch (error) {
    hide();
    // message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (id: number | undefined) => {
  const hide = message.loading('正在删除');
  if (!id) return true;
  try {
    await deleteData({
      id
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
function generateMonthArray(startMonth: string, endMonth: string): string[] {
  const start = new Date(`${startMonth}-01`);
  const end = new Date(`${endMonth}-01`);
  const monthArray: string[] = [];

  while (start <= end) {
    const year = start.getFullYear();
    const month = start.getMonth() + 1;
    const monthStr = `${year}-${(month < 10 ? '0' : '')}${month}`;
    monthArray.push(monthStr);

    start.setMonth(start.getMonth() + 1);
  }

  return monthArray;
}
const MaterialWin = ({ id }: any) => {
  const [btnLoading, setBtnLoading] = useState(false)
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [winProps, setWindowProps] = useState<any>({ title: '新建', id: null, record: {}, width: 480 })
  const [winPatchProps, setWindowPatchProps] = useState({ title: '批量创建', id: null, record: {}, open: false })
  const [form] = Form.useForm()
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<API.InsuredPersonItem[]>([]);
  const [months, setMonths] = useState({
    start: '',
    end: ''
  })
  const columns: ProColumns<API.InsuredPersonItem>[] = [
    {
      title: '缴费年份', dataIndex: 'paymentYear', valueType: 'digit', width: 100, ellipsis: true,
      renderFormItem: () => {
        return <InputNumber style={{ width: '50%' }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '缴费月份', dataIndex: 'paymentMonth', valueType: 'digit', width: 100, ellipsis: true,
      renderFormItem: () => {
        return <InputNumber style={{ width: '50%' }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '缴费基数', dataIndex: 'paymentBase', valueType: 'digit', width: 100, ellipsis: true,
      renderFormItem: (el, { record, recordKey }, rcForm) => {
        console.log(rcForm)
        return <InputNumber style={{ width: '50%' }} onChange={(value: number | null) => {
          const companyPayment = ((value || 0) * 16) / 100
          const personalPayment = (value || 0) * 8 / 100
          rcForm.setFieldsValue({ companyPayment, personalPayment })
        }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '单位缴纳', dataIndex: 'companyPayment', valueType: 'digit', width: 100, ellipsis: true,
      renderFormItem: () => {
        return <InputNumber style={{ width: '50%' }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '个人缴纳', dataIndex: 'personalPayment', valueType: 'digit', width: 100, ellipsis: true,
      renderFormItem: () => {
        return <InputNumber style={{ width: '50%' }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '缴费状态', dataIndex: 'paymentStatus', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 100,
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setWindowProps({ ...winProps, title: '编辑', id: record.id, record, width: 480 })
              handleModalVisible(true)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="温馨提示"
            description="确定删除该条数据？"
            okText="确定"
            cancelText="取消"
            onConfirm={async () => {
              await handleRemove(record.id);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <a color='red'>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];



  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        scroll={{ x: 800 }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setWindowPatchProps({ ...winProps, open: true, title: '批量创建', id: null, record: {} })
            }}
          >
            批量创建
          </Button>,
          // <Button
          //   key="1"
          //   type="primary"
          //   onClick={() => {
          //     setWindowProps({ ...winProps, title: '新建', id: null, record: {}, width: 480 })
          //     handleModalVisible(true)
          //   }}
          // >
          //   新建
          // </Button>,
        ]}
        request={async (params) => {
          const { data, success, total } = await queryList({
            ...params,
            insuredPersonId: id
          });
          return {
            data: data || [],
            success,
            total
          };
        }}
        columns={columns}
        rowSelection={{
          type: 'radio',
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      <CreateForm
        onCancel={() => {
          handleModalVisible(false)
        }}
        modalVisible={createModalVisible}
        {...winProps}
      >
        <ProTable<API.InsuredPersonItem, API.InsuredPersonItem>
          onSubmit={async (value) => {
            const success = await handleAdd(winProps.id, value, id);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}

          rowKey="id"
          type="form"
          form={{
            initialValues: winProps.record,
            labelAlign: 'left',
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        width={600}
        onCancel={() => {
          form.resetFields()
          setWindowPatchProps({ ...winPatchProps, open: false })
        }}
        modalVisible={winPatchProps.open}
        {...winPatchProps}
      >
        <Form layout='vertical' form={form} style={{ marginTop: 20 }} onFinish={async (values: any) => {
          setBtnLoading(true)
          const ms: string[] = generateMonthArray(months.start, months.end);
          let times = 0
          for (let item of ms) {
            const success = await handleAdd(winProps.id, { ...values, paymentYear: item.split('-')[0], paymentMonth: item.split('-')[1], }, id);
            if (success) {
              times++
            }
          }
          setTimeout(() => {
            if (times == ms.length) {
              message.success('提交成功')
              actionRef?.current?.reload();
              setBtnLoading(false)
              form.resetFields()
              setWindowPatchProps({ ...winPatchProps, open: false })
            }
            else {
              message.error('服务器出现异常')
              setBtnLoading(false)
            }
          }, 500);
        }}
        >
          <Form.Item
            label="缴费年月开始"
            name="startMonth"
            rules={[{ required: true, message: '请选择缴费年月开始!' }]}
          >
            <DatePicker picker="month" style={{ width: 200 }} onChange={(date, dateString) => {
              console.log(date, dateString);
              setMonths({ ...months, start: dateString })
            }} />
          </Form.Item>

          <Form.Item
            label="缴费年月结束"
            name="endMonth"
            rules={[{ required: true, message: '请选择缴费年月开始!' }]}
          >
            <DatePicker picker="month" style={{ width: 200 }} onChange={(date, dateString) => {
              console.log(date, dateString);
              setMonths({ ...months, end: dateString })
            }} />
          </Form.Item>
          <Form.Item
            label="缴费基数"
            name="paymentBase"
            rules={[{ required: true, message: '请输入缴费基数!' }]}
          >
            <InputNumber style={{ width: 200 }} min={1} onChange={(value: number | null) => {
              const companyPayment = ((value || 0) * 16) / 100
              const personalPayment = (value || 0) * 8 / 100
              form.setFieldsValue({ companyPayment, personalPayment })
            }} />
          </Form.Item>
          <Form.Item
            label="单位缴纳"
            name="companyPayment"
            rules={[{ required: true, message: '请输入缴费基数!' }]}
          >
            <InputNumber style={{ width: 200 }} />
          </Form.Item>
          <Form.Item
            label="个人缴纳"
            name="personalPayment"
            rules={[{ required: true, message: '请输入缴费基数!' }]}
          >
            <InputNumber style={{ width: 200 }} />
          </Form.Item>
          <Form.Item
            label="到账状态"
            name="paymentStatus"
            initialValue={'已到账'}
            rules={[{ required: true, message: '请输入到账状态!' }]}
          >
            <InputNumber style={{ width: 200 }} />
          </Form.Item>
          <Form.Item >
            <Button htmlType="button" style={{ margin: '0 8px' }} onClick={() => {
              form.resetFields()
            }}>
              重置
            </Button>
            <Button htmlType="submit" type="primary" loading={btnLoading}>
              提交
            </Button>
          </Form.Item>
        </Form>
      </CreateForm>
    </>
  );
}

export default MaterialWin;